angular.module('starter.controllers', [])

.controller('DashCtrl', function($scope,$rootScope,$ionicLoading,$state,$timeout,$ionicSlideBoxDelegate,JFHttp,User) {
  $scope.home={};
  $scope.user={};
  $scope.user.name=User.getUserInfo()|"游客";
  JFHttp.post({
    url:"http://106.14.30.199:8080/phone/home",
  }).then(function(result){
    var thome=result.data;
    thome.welcomeStr=thome.welcomeStr||"马上换一种方式，体验人生的与众不同。";
    thome.welcomeUrl=thome.welcomeUrl||"/img/home_top.png";
    $scope.home=thome;
    console.log(thome);
  },function(result){
    $ionicLoading.show({
      template:"获取首页信息失败",
      animation: 'fade-in',
      showBackdrop: true,
      maxWidth: 200,
      showDelay: 0,
      duration:2000
     });
  });
   $timeout(function(){
        $ionicSlideBoxDelegate.$getByHandle('slideimgs1').update();
         $ionicSlideBoxDelegate.$getByHandle('slideimgs').update();
       // $ionicSlideBoxDelegate.$getByHandle('slideimgs').loop(true);

    },1000);
  $scope.navToRouteInfo=function(index){
    console.log(index);
    $state.go("tab.routeinfo",{
      id:index,
    });
  };
  $scope.navToCityInfo=function(index){
    $state.go("cityrouteinfo",{
      id:index,
    });
  };
  
})
.controller('ChatsCtrl', function($scope,$ionicLoading,$rootScope,MSGService) {
  // alert(JSON.stringify( window.Wechat));
  //  window.Wechat.isInstalled(function (installed) {
  //   alert("Wechat installed: " + (installed ? "Yes" : "No"));
  // }, function (reason) {
  //   alert("Failed: " + reason);
  // });
  var dd=MSGService.getAllSessions();
  if(!dd){
    $ionicLoading.show({
      template:"您还没有任何聊天记录哦^_^",
      animation: 'fade-in',
      showBackdrop: true,
      maxWidth: 200,
      showDelay: 0,
      duration:2000
     });
  }
  $scope.chats=dd;
  MSGService.addMsgListener(function(msg){
    var msglength=dd.length;
    var ss=0;
     for( ss=0;ss<msglength;ss++){
       if(dd[ss].sessionId==msg.sessionId){
         dd[ss].lastMsg=msg.content;
         dd[ss].lastTime=msg.sendTime;
         break;
       }else if(ss==dd.length-1){
          var fffs={};
          fffs.lastTime=msg.sendTime;
          fffs.lastMsg=msg.content;
          fffs.sessionId=msg.sessionId;
          fffs.name=msg.sessionName;
          fffs.imgUrl=msg.imgUrl;
          dd.unshift(fffs);    
          break;
       }
     }
     $scope.chats=dd;
  });
  MSGService.addNoReadChangeListener(function(noReadArr){
    $rootScope.noReadArr=noReadArr;
    console.log($rootScope.noReadArr['total']);
  });
})

.controller('ChatDetailCtrl', function($scope, $rootScope, $stateParams,$ionicScrollDelegate,$ionicHistory,$timeout,$ionicLoading,MSGService,User) {
  $timeout(function(){
      $rootScope.hideTabs = true;
  },300);
  $scope.goBack=function(){
  	 $ionicHistory.goBack();
  }
  var sessionId = $stateParams.sessionId;
  if(!sessionId)return;
  $scope.msg="";
  var userId=User.getUserId();
  if(!userId)return;
  var msgs=MSGService.readSessionById(sessionId);
  console.log(msgs);
  $scope.msgs=msgs;
  var viewScroll = $ionicScrollDelegate.$getByHandle('messageDetailsScroll');
 $timeout(function(){
    $ionicScrollDelegate.scrollBottom();
 },300);
  $scope.sendMsg=function(msg){
    if(!msg)return;
    if("broadcast"==sessionId){
      $ionicLoading.show({
        template:"广播消息不能回复",
        animation: 'fade-in',
        showBackdrop: true,
        maxWidth: 200,
        showDelay: 0,
        duration:2000
      });
      return;
    }
    MSGService.sendMsgToSession(userId,sessionId,msg).then(function(result){
      msgs=null;
      $scope.msg='';
       $timeout(function(){
          $scope.msgs.push(result.data);
          $ionicScrollDelegate.scrollBottom();
       },300);
    },function(result){
      $ionicLoading.show({
        template:"发送消息失败",
        animation: 'fade-in',
        showBackdrop: true,
        maxWidth: 200,
        showDelay: 0,
        duration:2000
      });
    });
  }      
  $scope.doRefresh=function (params) {
     $timeout(function() {
        $scope.$broadcast('scroll.refreshComplete');
     }, 200);
  };
   MSGService.addMsgListener(function(msg){
     if(msg.sessionId==sessionId){
       $timeout(function(){
          $scope.msgs.push(msg);
          $ionicScrollDelegate.scrollBottom();
          MSGService=changNOReadNum(-1,sessionId);
       },300);
     }
     return true;
  });
})
/**
 * 我的
 */
.controller('AccountCtrl', function($scope,$state,User) {
   $scope.login=function(){
       $state.go("weilogin");
   };
  $scope.settings = {
    enableFriends: true,
  };
})
/**
 * 微信登陆
 */
.controller('WeiLoginCtrl', function($scope,$rootScope,$ionicHistory,$state,$ionicLoading,User,JFIM,MSGService) {
      $scope.$on('$ionicView.beforeEnter', function() {
        $rootScope.hideTabs=true;
      });
      $scope.navback=function (params) {
          $ionicHistory.goBack();
      };
      $scope.weiLogin=function(){
      User.login().then(function(data){
         JFIM.registIMHandle("ws://106.14.30.199:8080/ws",userId,function(ss){
        MSGService.onMsgReceive(ss);
      });
      MSGService.findAll(userId);
        $state.go("tab.account");
    },function(){
      alert("登陆失败")
    });
   }
})
.controller('ScheduleCtrl', function($scope,$state) {
  var jj={
    url:"11",
    from:"2016-12-13",
    to:"2016-12-16",
    name:"快乐旅行北京城",
    cost:"120.0",
    status:"已完成",
  }
  $scope.orderArr=[jj];
  $scope.goToOrder=function(id){
    $state.go("comment",{
      id:1,
    });
  }
})

.controller('RoutInfoCtrl', function($scope,$stateParams,$rootScope,$ionicPopover,$state,$ionicHistory,$ionicLoading,
MSGService,JFHttp,User) {
      $scope.$on('$ionicView.beforeEnter', function() {
        $rootScope.hideTabs=true;
      });
      $scope.navback=function (params) {
          $ionicHistory.goBack();
      }
      $scope.showSchedule=function(way){
        if(!way)return;
        var uid= (new Date()).valueOf();
	      localStorage.setItem(uid,JSON.stringify(way));
        $state.go("routetrip",{
          id:uid,
        });
      };
      $scope.showComment=function(arr){
        if(!arr)return;
        var uid= (new Date()).valueOf();
	      localStorage.setItem(uid,JSON.stringify(arr));
        $state.go("routecoment",{
          id:uid,
        });
      };
      $scope.showCostDetail=function(content){
        var uid= (new Date()).valueOf();
	      localStorage.setItem(uid,content);
         $state.go("routecost",{
           id:uid,
         });
      }
      $scope.showBackBook=function(content){
         var uid= (new Date()).valueOf();
	      localStorage.setItem(uid,content);
        $state.go("routecost",{
           id:uid,
         });
      }
      $scope.getBook=function(iid){
        $state.go("booktime",{
          id:iid,
        })
      }
      $scope.connect=function(way){
        var from=User.getUserId();
        MSGService.makeAsessionByUser(from,way.leaderId).then(function(result){
          $state.go("chat-detail",{
            sessionId:result.data.sessionId,
          })
        },function(result){
          
        });
      };
      var routeid=$stateParams.id;
      $scope.way={};
      JFHttp.post({
        url:"http://106.14.30.199:8080/route/getdetail",
        data:{
          id:routeid,
        }
      }).then(function(result){
        $scope.way=result.data;
        console.log($scope.way);
      },function(reuslt){
          $ionicLoading.show({
          template:"获取热门城市失败",
          animation: 'fade-in',
          showBackdrop: true,
          maxWidth: 200,
          showDelay: 0,
          duration:2000
        });
      });
})
/**
 * 线路行程查看 
 */
.controller('RouteTripInfoCtrl', function($scope,$stateParams,$rootScope,$state,$ionicHistory,$ionicLoading,JFHttp) {
      $scope.$on('$ionicView.beforeEnter', function() {
        $rootScope.hideTabs=true;
      });
      $scope.navback=function (params) {
          $ionicHistory.goBack();
      };
      var uid=$stateParams.id;
      var tjson=localStorage.getItem(uid);
      if(!tjson)return;
      $scope.way=JSON.parse(tjson);
      localStorage.removeItem(uid);
})
/**
 * 路线评论详情
 */
.controller('RouteCommentCtrl', function($scope,$stateParams,$rootScope,$state,$ionicHistory,$ionicLoading,JFHttp) {
      $scope.$on('$ionicView.beforeEnter', function() {
        $rootScope.hideTabs=true;
      });
      $scope.navback=function (params) {
          $ionicHistory.goBack();
      };
      var uid=$stateParams.id;
      var tjson=localStorage.getItem(uid);
      if(!tjson)return;
      $scope.wayArr=JSON.parse(tjson);
      localStorage.removeItem(uid);
})
/**
 * 线路费用详情
 */
.controller('CostDetailPCtrl', function($scope,$stateParams,$rootScope,$state,$ionicHistory,$ionicLoading,JFHttp) {
      $scope.$on('$ionicView.beforeEnter', function() {
        $rootScope.hideTabs=true;
      });
      $scope.navback=function (params) {
          $ionicHistory.goBack();
      };
      var uid=$stateParams.id;
      var tjson=localStorage.getItem(uid);
      if(!tjson)return;
       $scope.content=tjson;
      localStorage.removeItem(uid);
})
/**
 * 线路退订政策
 */
.controller('RouteBackCtrl', function($scope,$stateParams,$rootScope,$state,$ionicHistory,$ionicLoading,JFHttp) {
      $scope.$on('$ionicView.beforeEnter', function() {
        $rootScope.hideTabs=true;
      });
      $scope.navback=function (params) {
          $ionicHistory.goBack();
      };
      var uid=$stateParams.id;
      var tjson=localStorage.getItem(uid);
      if(!tjson)return;
      $scope.content=tjson;
      localStorage.removeItem(uid);
})
/**
 * 搜索目的地
 */
.controller('searchCtrl', function($scope,$rootScope,$state,$ionicLoading,JFHttp) {
      
      $scope.$on('$ionicView.beforeEnter', function() {
        $rootScope.hideTabs=true;
      });
      $scope.destArr=[];
      $scope.goToDest=function(id){
         $state.go("searchinfo",{id:id});
      }
      JFHttp.post({
        url:"http://106.14.30.199:8080/dest/maindest"
      }).then(function(result){
        $scope.destArr=result.data;
      },function(result){
        $ionicLoading.show({
          template:"获取热门城市失败",
          animation: 'fade-in',
          showBackdrop: true,
          maxWidth: 200,
          showDelay: 0,
          duration:2000
        });
      });
})
/**
 * 搜索详情页
 */
.controller('searchinfoCtrl', function($scope,$stateParams,$state,$ionicHistory,$ionicLoading,JFHttp) {
      $scope.wayArr=[];
     // alert($stateParams.id);
      var destid =$stateParams.id||1;
	 $scope.goBack=function(){
	 	$ionicHistory.goBack();
	 }
      $scope.goToDest=function(id){
        $state.go("tab.routeinfo",{
          id:id,
        });
      }
      JFHttp.post({
        url:"http://106.14.30.199:8080/route/getby/cityid",
        data:{
          destId:destid
        }
      }).then(function(result){
        console.log(result.data);
        $scope.wayArr=result.data;
      },function(result){
        $ionicLoading.show({
          template:"搜索失败",
          animation: 'fade-in',
          showBackdrop: true,
          maxWidth: 200,
          showDelay: 0,
          duration:2000
        });
      });
})
/**
 * 预约时间选择
 */
.controller('BookTimeCtrl', function($scope,$stateParams,$rootScope,$state,$ionicHistory,$ionicLoading,$timeout,ionicDatePicker,User,JFHttp) {
      $scope.$on('$ionicView.beforeEnter', function() {
        $rootScope.hideTabs=true;
      });
      $scope.navback=function (params) {
          $ionicHistory.goBack();
      };
      $scope.startTime="开始时间";
      $scope.endTime="结束时间";
      var stratobj,endobj;
       var uid=$stateParams.id;
      // var tjson=localStorage.getItem(uid);
      // if(!tjson)return;
      //  $scope.content=tjson;
      // localStorage.removeItem(uid);
      var startflag,endflag;
      var stratobj={
         callback: function (val) {
           startflag=1;
           $scope.startTime=new Date(val).format("yyyy-MM-dd");
           endobj.from=new Date(val);
           endobj.to="";
        },
      };
      var endobj={
         callback: function (val) {
           endflag=1;
           $scope.endTime=new Date(val).format("yyyy-MM-dd");
           stratobj.to=new Date(val);
           stratobj.from=new Date();
        },
      };
      $scope.toStartTime=function(){
        ionicDatePicker.openDatePicker(stratobj);
      };
      $scope.toEndTime=function(){
        ionicDatePicker.openDatePicker(endobj);
      }
      $scope.addOrder=function(){
        if(!startflag||!endflag||endflag+startflag<2){
           $ionicLoading.show({
            template:"请选择您希望出行的时间",
            animation: 'fade-in',
            showBackdrop: true,
            maxWidth: 200,
            showDelay: 0,
            duration:2000
          });
          return;
        }
        var userId=User.getUserId();
        var upload={
          userId:userId,
          routeInfoId:uid,
          startTime: $scope.startTime,
          endTime: $scope.endTime,
        };
        JFHttp.post({
          url:"http://106.14.30.199:8080/order/add",
          data:upload,
        }).then(function(result){
            $ionicLoading.show({
            template:"预约成功，请等候我们的审核",
            animation: 'fade-in',
            showBackdrop: true,
            maxWidth: 200,
            showDelay: 0,
            duration:2000
          });
          $timeout(function(){
             $ionicHistory.goBack();
          },2000);
          
        },function(result){
          var tmpStr="预约失败，请稍候再试";
          if(result.status=="403")tmpStr="在这个时间段你已经预约其他的旅行";
          $ionicLoading.show({
            template:tmpStr,
            animation: 'fade-in',
            showBackdrop: true,
            maxWidth: 200,
            showDelay: 0,
            duration:2000
          });
        });
      }
      
})


.controller('CommentCtrl', function($scope,$stateParams,$state,$ionicLoading,JFHttp) {
      $scope.comment={};
      $scope.comment.url="11";
})
;
